package com.qikecn.uploadfilebybase64.client;

import it.sauronsoftware.base64.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.qikecn.uploadfilebybase64.HttpClientUtil;
import com.qikecn.uploadfilebybase64.UploadResultBean;

public class ClientUplaod {
	
	/**
	 * 客户端上传文件接口
	 * 可以上传的文件类型：jpg,jpeg,gif,png,zip,war,doc,docx,ppt,pptx,xls,xlsx等
	 * @param url 服务器接口地址
	 * @param localFiles 本地待上传文件列表
	 * @return
	 * @throws JSONException
	 */
	public static List<UploadResultBean> upload(String url, List<File> localFiles) throws JSONException{
		//上传结果
		List<UploadResultBean> list = new ArrayList<UploadResultBean>();
		//组合接口请求数据
		JSONArray array = new JSONArray();
		for(File file : localFiles){
			UploadResultBean bean = new UploadResultBean();
			if(file == null || !file.exists()){
				bean.setRet(450);
				bean.setMsg("文件不存在");
				bean.setLocalFilePath(file.getAbsolutePath());
				list.add(bean);
			}else {
				String data = getFileBase64Data(file);
				if(data == null || data.equals("")){
					bean.setRet(451);
					bean.setMsg("获取文件信息为空");
					bean.setLocalFilePath(file.getAbsolutePath());
					list.add(bean);
				}else {
					JSONObject object = new JSONObject();
					object.put("localFilePath", file.getAbsolutePath());
					object.put("base64Data", data);
					array.put(object);
				}
			}
		}
		//post上传图片
		String result = HttpClientUtil.simpleHttpPost(url, "array="+array.toString());
		JSONArray resultArray = new JSONArray(result);
		for(int i=0;i<resultArray.length();i++){
			JSONObject resultObject = resultArray.getJSONObject(i);
			UploadResultBean bean = new UploadResultBean();
			bean.setRemoteFileName(resultObject.has("remoteFileName")?resultObject.getString("remoteFileName"):"");
			bean.setLocalFilePath(resultObject.has("localFilePath")?resultObject.getString("localFilePath"):"");
			bean.setRet(resultObject.has("ret")?resultObject.getInt("ret"):0);
			bean.setMsg(resultObject.has("msg")?resultObject.getString("msg"):"");
			list.add(bean);
		}
		return list;
	}
	
	/**
	 * 将文件转成base64字符串
	 * @param file
	 * @return
	 */
	public static String getFileBase64Data(File file){
		String data = "";
		FileInputStream inputFile = null;
		try {
			inputFile = new FileInputStream(file);
			byte[] buffer = new byte[(int) file.length()];
			inputFile.read(buffer);
			data = new String(Base64.encode(buffer), "UTF-8");
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("getFileBase64Data Exception:"+e.getClass().getName());
			e.printStackTrace();
		}finally{
			if(inputFile != null){
				try {
					inputFile.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return data;
	}
	
}
